<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
        Java-framework-ActiveMQ - rulerLwx Blog
      </title>
        <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-transform" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    
    <meta name="theme-color" content="#000000" />
    
    <meta http-equiv="window-target" content="_top" />
    
    
    <meta name="description" content="基础知识 消息协议/规范 JMS JMS即Java消息服务（Java Message Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的" />
    <meta name="generator" content="Hugo 0.73.0 with theme pure" />
    <title>Java-framework-ActiveMQ - rulerLwx Blog</title>
    
    
    <link rel="stylesheet" href="https://rulerLwx.gitee.io/css/style.min.c4bc7071f132c964c2116bca53b392933f377e5ca7b7051ed245187c621a2d3e.css">
    
    <link rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/9.15.10/styles/github.min.css" async>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.css" async>
    <meta property="og:title" content="Java-framework-ActiveMQ" />
<meta property="og:description" content="基础知识 消息协议/规范 JMS JMS即Java消息服务（Java Message Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://rulerLwx.gitee.io/2019/08/java-framework-activemq/" />
<meta property="article:published_time" content="2019-08-01T11:01:30+08:00" />
<meta property="article:modified_time" content="2019-08-01T11:01:30+08:00" />
<meta itemprop="name" content="Java-framework-ActiveMQ">
<meta itemprop="description" content="基础知识 消息协议/规范 JMS JMS即Java消息服务（Java Message Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的">
<meta itemprop="datePublished" content="2019-08-01T11:01:30&#43;08:00" />
<meta itemprop="dateModified" content="2019-08-01T11:01:30&#43;08:00" />
<meta itemprop="wordCount" content="3447">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Java-framework-ActiveMQ"/>
<meta name="twitter:description" content="基础知识 消息协议/规范 JMS JMS即Java消息服务（Java Message Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的"/>

    <!--[if lte IE 9]>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
      <![endif]-->

    <!--[if lt IE 9]>
        <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
      <![endif]-->
  </head>

  
  

  <body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage"><header class="header" itemscope itemtype="http://schema.org/WPHeader">
    <div class="slimContent">
      <div class="navbar-header">
        <div class="profile-block text-center">
          <a id="avatar" href="https://gitee.com/rulerLwx" target="_blank">
            <img class="img-circle img-rotate" src="https://rulerLwx.gitee.io/avatar.png" width="200" height="200">
          </a>
          <h2 id="name" class="hidden-xs hidden-sm">rulerLwx</h2>
          <h3 id="title" class="hidden-xs hidden-sm hidden-md">thinking...</h3>
          <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i>Guangzhou, China</small>
        </div><div class="search" id="search-form-wrap">
    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i
                        class="icon icon-search"></i></button>
            </span>
        </div>
        <div class="ins-search">
            <div class="ins-search-mask"></div>
            <div class="ins-search-container">
                <div class="ins-input-wrapper">
                    <input type="text" class="ins-search-input" placeholder="Type something..."
                        x-webkit-speech />
                    <button type="button" class="close ins-close ins-selectable" data-dismiss="modal"
                        aria-label="Close"><span aria-hidden="true">×</span></button>
                </div>
                <div class="ins-section-wrapper">
                    <div class="ins-section-container"></div>
                </div>
            </div>
        </div>
    </form>
</div>
        <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
      </div>
      <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
        <ul class="nav navbar-nav main-nav">
            <li class="menu-item menu-item-home">
                <a href="/">
                    <i class="icon icon-home-fill"></i>
                  <span class="menu-title">Home</span>
                </a>
            </li>
            <li class="menu-item menu-item-archives">
                <a href="/posts/">
                    <i class="icon icon-archives-fill"></i>
                  <span class="menu-title">Archives</span>
                </a>
            </li>
            <li class="menu-item menu-item-categories">
                <a href="/categories/">
                    <i class="icon icon-folder"></i>
                  <span class="menu-title">Categories</span>
                </a>
            </li>
            <li class="menu-item menu-item-tags">
                <a href="/tags/">
                    <i class="icon icon-tags"></i>
                  <span class="menu-title">Tags</span>
                </a>
            </li>
            <li class="menu-item menu-item-about">
                <a href="/about/">
                    <i class="icon icon-cup-fill"></i>
                  <span class="menu-title">About</span>
                </a>
            </li>
        </ul>
      </nav>
    </div>
  </header>

<aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">enjoy~
            </div>
        </div>
    </div>
</div>

      <div class="widget">
    <h3 class="widget-title"> Categories</h3>
    <div class="widget-body">
        <ul class="category-list">
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-framework/" class="category-list-link">java-framework</a><span class="category-list-count">38</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-front-end/" class="category-list-link">java-front-end</a><span class="category-list-count">11</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-se/" class="category-list-link">java-se</a><span class="category-list-count">21</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/java-senior/" class="category-list-link">java-senior</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/linux/" class="category-list-link">linux</a><span class="category-list-count">13</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/tools/" class="category-list-link">tools</a><span class="category-list-count">1</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E7%83%A9/" class="category-list-link">技术杂烩</a><span class="category-list-count">4</span></li>
            <li class="category-list-item"><a href="https://rulerLwx.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" class="category-list-link">数据库</a><span class="category-list-count">15</span></li>
        </ul>
    </div>
</div>
      <div class="widget">
    <h3 class="widget-title"> Tags</h3>
    <div class="widget-body">
        <ul class="tag-list">
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/jvm/" class="tag-list-link">jvm</a><span
                    class="tag-list-count">1</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="tag-list-link">多线程</a><span
                    class="tag-list-count">2</span></li>
            
            
            <li class="tag-list-item"><a href="https://rulerLwx.gitee.io/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/" class="tag-list-link">网络编程</a><span
                    class="tag-list-count">3</span></li>
            
        </ul>

    </div>
</div>
      
<div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
        <ul class="recent-post-list list-unstyled no-thumbnail">
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%87%AA%E5%B7%B1%E5%8A%A8%E6%89%8B%E4%B8%80%E6%89%B9%E9%87%8F%E7%A7%BB%E5%8A%A8%E9%87%8D%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6/" class="title">自己动手（一）——批量移动、重命名文件</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-27 17:50:02 &#43;0800 CST" itemprop="datePublished">2020-07-27</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E5%85%B3%E4%BA%8Einteger%E7%9A%84-128~127%E7%BC%93%E5%AD%98/" class="title">关于Integer的 -128~127缓存</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-11 16:56:21 &#43;0800 CST" itemprop="datePublished">2020-07-11</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98/" class="title">跨域问题</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-08 22:41:12 &#43;0800 CST" itemprop="datePublished">2020-07-08</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/%E4%B8%AA%E4%BA%BA%E5%8D%9A%E5%AE%A2%E6%90%AD%E5%BB%BA/" class="title">个人博客搭建</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-05 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-05</time>
                    </p>
                </div>
            </li>
            <li>
                <div class="item-inner">
                    <p class="item-title">
                        <a href="https://rulerLwx.gitee.io/2020/07/mongodb-1/" class="title">MonggoDB-1</a>
                    </p>
                    <p class="item-date">
                        <time datetime="2020-07-03 18:58:47 &#43;0800 CST" itemprop="datePublished">2020-07-03</time>
                    </p>
                </div>
            </li>
        </ul>
    </div>
</div>
  </div>
</aside>

    
    
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <h4 class="toc-title">Catalogue</h4>
    <nav id="toc" class="js-toc toc">

    </nav>
  </div>
</aside>
<main class="main" role="main"><div class="content">
  <article id="-" class="article article-type-" itemscope
    itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      <h1 itemprop="name">
  <a
    class="article-title"
    href="/2019/08/java-framework-activemq/"
    >Java-framework-ActiveMQ</a
  >
</h1>

      <div class="article-meta">
        
<span class="article-date">
  <i class="icon icon-calendar-check"></i>&nbsp;
<a href="https://rulerLwx.gitee.io/2019/08/java-framework-activemq/" class="article-date">
  <time datetime="2019-08-01 11:01:30 &#43;0800 CST" itemprop="datePublished">2019-08-01</time>
</a>
</span>
<span class="article-category">
  <i class="icon icon-folder"></i>&nbsp;
  <a class="article-category-link" href="/categories/java-framework/"> Java-framework </a>
</span>

        <span class="post-comment"><i class="icon icon-comment"></i>&nbsp;<a href="/2019/08/java-framework-activemq/#comments"
            class="article-comment-link">Comments</a></span>
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 3447words</span>
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 7minutes </span>
      </div>
    </div>
    <div class="article-entry marked-body js-toc-content" itemprop="articleBody">
      <h1 id="基础知识">基础知识</h1>
<h2 id="消息协议规范">消息协议/规范</h2>
<h3 id="jms">JMS</h3>
<blockquote>
<p>JMS即Java消息服务（Java Message Service）应用程序接口，是一个Java平台中关于面向消息中间件（MOM）的API，用于在两个应用程序之间，或分布式系统中发送消息，进行异步通信。Java消息服务是一个与具体平台无关的API，绝大多数MOM提供商都对JMS提供支持。&mdash;百度百科</p>
</blockquote>
<p>相关概念</p>
<ul>
<li>消费者/订阅者：接收并处理消息的客户端</li>
<li>消息：应用程序之间传递的数据内容</li>
<li>消息模式：在客户端之间传递消息的方式，<strong>主题模式</strong>和<strong>队列模式</strong>。</li>
</ul>
<p>主题模式：</p>
<ul>
<li>客户端包括发布者和订阅者</li>
<li>主题中的消息被所有订阅者消费</li>
<li>消息者不能消费订阅之前的消息</li>
</ul>
<p>队列模式：</p>
<ul>
<li>客户端包括生产者和消费者</li>
<li>队列中的消息只能被一个消费者消费</li>
<li>消息者可以随时消费队列中的消息</li>
</ul>
<p>JMS编码接口：</p>
<ul>
<li>ConnectionFactory:创建连接消息中间件工厂</li>
<li>Connection:应用程序与消息服务器之间的通信链路</li>
<li>Destination:消息发布和接收的地点，包括队列和主题</li>
<li>Session:会话，单线程的上下文，用于发送和接收消息</li>
<li>MessageConsumer:由会话创建，用于接收发送到目标的消息</li>
<li>MessageProducer:由会话创建，用于发送消息到目标</li>
<li>Message:在消息者和生产者之间传送的对象，消息头，一组消息属性，一个消息体</li>
</ul>
<p>JMS编码接口之间的关系：</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708074648.png" alt=""></p>
<h3 id="amqp">AMQP</h3>
<blockquote>
<p>AMQP，即Advanced Message Queuing Protocol,一个提供统一消息服务的应用层标准高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计。基于此协议的客户端与消息中间件可传递消息，并不受客户端/中间件不同产品，不同的开发语言等条件的限制。Erlang中的实现有 RabbitMQ等。&mdash;百度百科</p>
</blockquote>
<p>JMS &amp; AMQP:</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708074751.png" alt=""></p>
<h2 id="协议规范实现者">协议/规范实现者</h2>
<p>ActiveMQ &amp; RabitMQ &amp; Kafka:</p>
<p><img src="https://gitee.com/rulerLwx/PicGo/raw/master/img/20200708074814.png" alt=""></p>
<h2 id="消息中间件好处">消息中间件好处</h2>
<ul>
<li>解耦</li>
<li>异步</li>
<li>横向扩展</li>
</ul>
<h1 id="activemq">ActiveMQ</h1>
<h2 id="activemq下载安装">ActiveMQ下载安装</h2>
<p><a href="%5Bhttp://activemq.apache.org/activemq-5151-release.html%5D">Apache ActiveMQ</a>官网下载，下载ActiveMQ 5.15.1 windows版本，解压，进入MQ的bin目录\bin\win64，</p>
<p>启动服务：</p>
<ul>
<li>非Windows服务方式：双击<code>\bin\win64\activemq.bat</code>启动服务</li>
<li>以Windows服务方式：双击<code>\bin\win64\InstallService.bat</code>安装服务，然后到windows服务中开启服务。若要卸载服务，双击执行<code>\bin\win64\UninstallService.bat</code>。</li>
</ul>
<p>在浏览器访问<code>http://127.0.0.1:8161/</code>，测试安装是否成功，</p>
<h2 id="demo">Demo</h2>
<p>maven:</p>
<pre><code class="language-xml">        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.activemq&lt;/groupId&gt;
            &lt;artifactId&gt;activemq-all&lt;/artifactId&gt;
            &lt;version&gt;5.15.1&lt;/version&gt;
        &lt;/dependency&gt;
</code></pre>
<h3 id="消息队列">消息队列</h3>
<p>生产者：</p>
<pre><code class="language-java">public class AppProducer {
    private static final String url = &quot;tcp://192.168.0.103:61616&quot;; //61616是ActiveMQ默认的端口
    private static final String queueName = &quot;queue-test&quot;;

    public static void main(String[] args) throws JMSException {
        //1. 创建ConnectionFaction
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

        //2. 创建Connection
        Connection connection = connectionFactory.createConnection();

        //3. 启动连接
        connection.start();

        //4. 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //5. 创建一个目标
        Destination destination = session.createQueue(queueName);

        //6. 创建一个生产者
        MessageProducer producer = session.createProducer(destination);

        for(int i = 0;i &lt; 100; i++) {
            //7. 创建消息
            TextMessage textMessage = session.createTextMessage(&quot;test &quot; + i);
            //8. 发布消息
            producer.send(textMessage);

            System.out.println(&quot;发送消息：&quot;+textMessage.getText());
        }

        //9. 关闭连接
        connection.close();
    }
}
</code></pre>
<p>消费者：</p>
<pre><code class="language-java">public class AppConsumer {
    private static final String url = &quot;tcp://192.168.0.103:61616&quot;; //61616是ActiveMQ默认的端口
    private static final String queueName = &quot;queue-test&quot;;

    public static void main(String[] args) throws JMSException {
        //1. 创建ConnectionFaction
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

        //2. 创建Connection
        Connection connection = connectionFactory.createConnection();

        //3. 启动连接
        connection.start();

        //4. 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //5. 创建一个目标
        Destination destination = session.createQueue(queueName);

        //6. 创建一个消费者
        MessageConsumer consumer = session.createConsumer(destination);

        //7. 创建一个监听器
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println(&quot;接收到的消息：&quot;+((TextMessage) message).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        //8. 关闭连接
        //connection.close(); //不能直接关闭，因此上面的监听器是个异步的过程，关闭后就接收不到消息
    }
</code></pre>
<h3 id="主题队列">主题队列</h3>
<p>发布者：</p>
<pre><code class="language-java">public class AppProducer {
    private static final String url = &quot;tcp://192.168.0.103:61616&quot;; //61616是ActiveMQ默认的端口
    private static final String topicName = &quot;topic-test&quot;;

    public static void main(String[] args) throws JMSException {
        //1. 创建ConnectionFaction
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

        //2. 创建Connection
        Connection connection = connectionFactory.createConnection();

        //3. 启动连接
        connection.start();

        //4. 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //5. 创建一个目标
        Destination destination = session.createTopic(topicName);

        //6. 创建一个生产者
        MessageProducer producer = session.createProducer(destination);

        for(int i = 0;i &lt; 100; i++) {
            //7. 创建消息
            TextMessage textMessage = session.createTextMessage(&quot;test &quot; + i);
            //8. 发布消息
            producer.send(textMessage);

            System.out.println(&quot;发送消息：&quot;+textMessage.getText());
        }

        //9. 关闭连接
        connection.close();
    }
}
</code></pre>
<p>订阅者：</p>
<pre><code class="language-java">public class AppConsumer {
    private static final String url = &quot;tcp://192.168.0.103:61616&quot;; //61616是ActiveMQ默认的端口
    private static final String topicName = &quot;topic-test&quot;;

    public static void main(String[] args) throws JMSException {
        //1. 创建ConnectionFaction
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);

        //2. 创建Connection
        Connection connection = connectionFactory.createConnection();

        //3. 启动连接
        connection.start();

        //4. 创建会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        //5. 创建一个目标
        Destination destination = session.createTopic(topicName);

        //6. 创建一个消费者
        MessageConsumer consumer = session.createConsumer(destination);

        //7. 创建一个监听器
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                TextMessage textMessage = (TextMessage) message;
                try {
                    System.out.println(&quot;接收到的消息：&quot;+((TextMessage) message).getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        //8. 关闭连接
        //connection.close(); //不能直接关闭，因此上面的监听器是个异步的过程，关闭后就接收不到消息
    }
}
</code></pre>
<p>注：发布者、订阅者的代码复制自<strong>消息队列</strong>中的代码，修改的只是<code>Destination destination = session.createTopic(topicName);</code>这行代码及涉及到的topicName名称。</p>
<h2 id="spring--activemq">Spring + ActiveMQ</h2>
<p>首先，要了解Spring提供的JMS的接口：</p>
<ul>
<li>ConnectionFactory:用于管理连接</li>
<li>JmsTemplate:发送、接收消息的模板</li>
<li>MessageListener:消息监听器</li>
</ul>
<p>ConnectionFactory，是Spring提供的JMS连接池，它的子类有：</p>
<ul>
<li>SingleConnectionFactory</li>
<li>CachingConnectionFactory</li>
</ul>
<p>JmsTemplate，我们只需向Spring容器注删这个类，就可以使用JmsTemplate，它是线程安全的类，可以在整个范围内使用。</p>
<p>MessageListener，我们只需实现它的一个<code>onMessage</code>方法，该方法只接收一个Message参考。</p>
<h3 id="队列模式">队列模式</h3>
<p>项目结构：</p>
<pre><code class="language-text">src
    main
        java
            com.demo.jms
                consumer
                    AppConsumer
                    ConsumerMessageListener
                producer
                    AppProducer
                    ProducerService
                    ProducerServiceImpl
        resources
            common.xml
            consumer.xml
            producer.xml
pom.xml
</code></pre>
<p>依赖之pom.xml：</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

    &lt;groupId&gt;com.demo.jms&lt;/groupId&gt;
    &lt;artifactId&gt;jms-spring&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

    &lt;properties&gt;
        &lt;spring.version&gt;4.0.8.RELEASE&lt;/spring.version&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;version&gt;4.11&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;!--本次demo的主角--&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-jms&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
            &lt;version&gt;${spring.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.activemq&lt;/groupId&gt;
            &lt;artifactId&gt;activemq-core&lt;/artifactId&gt;
            &lt;version&gt;5.7.0&lt;/version&gt;
            &lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
                    &lt;artifactId&gt;spring-context&lt;/artifactId&gt;
                &lt;/exclusion&gt;
            &lt;/exclusions&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

&lt;/project&gt;
</code></pre>
<p>生产者接口：</p>
<pre><code class="language-java">public interface ProducerService {
    void setMessage(String message);
}
</code></pre>
<p>生产者接口实现类：</p>
<pre><code class="language-java">import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import javax.annotation.Resource;
import javax.jms.*;

/**
 * Created by lwx on 2017/10/7.
 */
public class ProducerServiceImpl implements ProducerService {

    @Autowired
    JmsTemplate jmsTemplate;
    @Resource(name = &quot;queueDistination&quot;)//第一处修改，将name = &quot;topicDistination&quot;时，则为主题模式
    Destination destination;

    public void setMessage(final String message) {
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                TextMessage textMessage = session.createTextMessage(message);
                return textMessage;
            }
        });
        System.out.println(&quot;发送消息：&quot;+message);
    }
}
</code></pre>
<p>Spring配置文件之common.xml:</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd&quot;&gt;

    &lt;context:annotation-config/&gt;

    &lt;!--ActiveMQ为我们提供的ConnectionFactory--&gt;
    &lt;bean id=&quot;targetConnectionFactory&quot; class=&quot;org.apache.activemq.ActiveMQConnectionFactory&quot;&gt;
        &lt;property name=&quot;brokerURL&quot; value=&quot;tcp://192.168.0.103:61616&quot;/&gt;
    &lt;/bean&gt;

    &lt;!--Spring为我们提供的连接池--&gt;
    &lt;bean id=&quot;connectionFactory&quot; class=&quot;org.springframework.jms.connection.SingleConnectionFactory&quot;&gt;
        &lt;property name=&quot;targetConnectionFactory&quot; ref=&quot;targetConnectionFactory&quot;/&gt;
    &lt;/bean&gt;

    &lt;!--一个队列目的地，点对点--&gt;
    &lt;bean id=&quot;queueDistination&quot; class=&quot;org.apache.activemq.command.ActiveMQQueue&quot;&gt;
        &lt;!--队列的名称--&gt;
        &lt;constructor-arg value=&quot;queue&quot;/&gt;
    &lt;/bean&gt;

    &lt;!--一个主题目的地，发布订阅模式--&gt;
    &lt;bean id=&quot;topicDistination&quot; class=&quot;org.apache.activemq.command.ActiveMQTopic&quot;&gt;
        &lt;constructor-arg value=&quot;topic&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<p>Spring配置文件之生产者producer.xml:</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;

    &lt;import resource=&quot;common.xml&quot;/&gt;

    &lt;!--配置JmsTemplate，用于发送消息--&gt;
    &lt;bean id=&quot;jmsTemplate&quot; class=&quot;org.springframework.jms.core.JmsTemplate&quot;&gt;
        &lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot;/&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;producerService&quot; class=&quot;com.demo.jms.producer.ProducerServiceImpl&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<p>生产者测试类AppProducer.java:</p>
<pre><code class="language-java">public class AppProducer {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(&quot;producer.xml&quot;);
        ProducerService service = context.getBean(ProducerService.class);
        for(int i = 0; i&lt;100; i++) {
            service.setMessage(&quot;test &quot;+i);
        }
        context.close();
    }
}
</code></pre>
<p>消费者消息监听器ConsumerMessageListener.java:</p>
<pre><code class="language-java">import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

/**
 * Created by lwx on 2017/10/7.
 */
public class ConsumerMessageListener implements MessageListener {
    public void onMessage(Message message) {
        TextMessage textMessage = (TextMessage) message;
        try {
            System.out.println(&quot;接收到的消息：&quot;+textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}
</code></pre>
<p>Spring配置文件之消费者consumer.xml:</p>
<pre><code class="language-xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
       xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd&quot;&gt;

    &lt;import resource=&quot;common.xml&quot;/&gt;

    &lt;!--配置消息监听器--&gt;
    &lt;bean id=&quot;consumerMessageListener&quot; class=&quot;com.demo.jms.consumer.ConsumerMessageListener&quot;/&gt;

    &lt;!--配置消息容器--&gt;
    &lt;bean id=&quot;jmsContainer&quot; class=&quot;org.springframework.jms.listener.DefaultMessageListenerContainer&quot;&gt;
        &lt;property name=&quot;connectionFactory&quot; ref=&quot;connectionFactory&quot;/&gt;

        &lt;!--第二处修改，ref=&quot;topicDistination&quot;时，则为主题模式--&gt;
        &lt;property name=&quot;destination&quot; ref=&quot;queueDistination&quot;/&gt;

        &lt;property name=&quot;messageListener&quot; ref=&quot;consumerMessageListener&quot;/&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
</code></pre>
<p>消费者之测试类AppConsumer.java:</p>
<pre><code class="language-java">public class AppConsumer {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(&quot;consumer.xml&quot;);
    }
}
</code></pre>
<p>注意：要开启ActiveMQ服务。</p>
<h3 id="主题模式">主题模式</h3>
<p>将<strong>队列模式</strong>中的<strong>第一处修改</strong>，<strong>第二处修改</strong>改好即可。</p>
<h1 id="faq">FAQ</h1>
<ul>
<li>
<p>什么是中间件</p>
<p>非底层操作系统软件，非业务应用软件，不直接给最终用户使用，不直接给客户带来价值的软件统称为中间件。</p>
</li>
</ul>

    </div>
    <div class="article-footer">
<blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-link hidden-xs">
      <strong>Permalink: </strong>
      <a href="https://rulerLwx.gitee.io/2019/08/java-framework-activemq/" title="Java-framework-ActiveMQ" target="_blank" rel="external">https://rulerLwx.gitee.io/2019/08/java-framework-activemq/</a>
    </li>
    <li class="post-copyright-license">
      <strong>License：</strong><a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN</a>
    </li>
  </ul>
</blockquote>

<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/rulerLwx" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://rulerLwx.gitee.io/avatar.png" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/rulerLwx" target="_blank"><span class="text-dark">rulerLwx</span><small class="ml-1x">thinking...</small></a></h3>
        <div>Good Good Study, Day Day Up~</div>
      </div>
    </figure>
  </div>
</div>
    </div>
  </article>
<section id="comments">
    <div id="vcomments"></div>
</section>

</div><nav class="bar bar-footer clearfix" data-stick-bottom>
    <div class="bar-inner">
        <ul class="pager pull-left">
            <li class="prev">
                <a href="https://rulerLwx.gitee.io/2018/06/java-front-vue-8-webpack/" title="Java-front-VUE-8-Webpack"><i
                        class="icon icon-angle-left"
                        aria-hidden="true"></i><span>&nbsp;&nbsp;Older</span></a>
            </li>
            <li class="next">
                <a href="https://rulerLwx.gitee.io/2019/08/java-framework-hibernate/"
                    title="Java-framework-Hibernate"><span>Newer&nbsp;&nbsp;</span><i
                        class="icon icon-angle-right" aria-hidden="true"></i></a>
            </li>
            
            <li class="toggle-toc">
                <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false"
                    title="Catalogue" role="button">
                    <span>[&nbsp;</span><span>Catalogue</span>
                    <i class="text-collapsed icon icon-anchor"></i>
                    <i class="text-in icon icon-close"></i>
                    <span>]</span>
                </a>
            </li>
        </ul>
        <div class="bar-right">
            <div class="share-component" data-sites="weibo,qq,wechat"
                data-mobile-sites="weibo,qq,qzone"></div>
        </div>
    </div>
</nav>

</main><footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
<ul class="social-links">
    <li><a href="https://gitee.com/rulerLwx" target="_blank" title="gitee" data-toggle=tooltip data-placement=top >
            <i class="icon icon-gitee"></i></a></li>
    <li><a href="https://github.com/wolf-lea" target="_blank" title="github" data-toggle=tooltip data-placement=top >
            <i class="icon icon-github"></i></a></li>
</ul>
  <div class="copyright">
    &copy;2017  -
    2020
    <div class="publishby">
        Theme by <a href="https://github.com/xiaoheiAh" target="_blank"> xiaoheiAh </a>base on<a href="https://github.com/xiaoheiAh/hugo-theme-pure" target="_blank"> pure</a>.
    </div>
  </div>
</footer>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_SVG"></script>
<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
            showMathMenu: false, //disables context menu
            tex2jax: {
            inlineMath: [ ['$','$'], ['\\(','\\)'] ]
           }
    });
</script>


<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
    window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/highlight.min.js"></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/python.min.js" defer></script>
<script type="text/javascript" src="https://cdn.staticfile.org/highlight.js/9.15.10/languages/javascript.min.js" defer></script><script>
    hljs.configure({
        tabReplace: '    ', 
        classPrefix: ''     
        
    })
    hljs.initHighlightingOnLoad();
</script>
<script src="https://rulerLwx.gitee.io/js/application.min.bdeb64b910570b6c41badc6a05b7afb0c8ad9efd8525de3c7257d59e786326a3.js"></script>
<script src="https://rulerLwx.gitee.io/js/plugin.min.51ff8c7317566f82259170fa36e09c4493adc9b9378b427a01ad3f017ebac7dd.js"></script>

<script>
    (function (window) {
        var INSIGHT_CONFIG = {
            TRANSLATION: {
                POSTS: 'Posts',
                PAGES: 'Pages',
                CATEGORIES: 'Categories',
                TAGS: 'Tags',
                UNTITLED: '(Untitled)',
            },
            ROOT_URL: 'https:\/\/rulerLwx.gitee.io',
            CONTENT_URL: 'https:\/\/rulerLwx.gitee.io\/searchindex.json ',
        };
        window.INSIGHT_CONFIG = INSIGHT_CONFIG;
    })(window);
</script>
<script type="text/javascript" src="https://rulerLwx.gitee.io/js/insight.min.a343cd9a5a7698336b28ef3a7c16a3a1b1d2d5fb17dc8ed04022bbe08cc5459073a15bdafa3a8a58cdd56080784bdd69fa70b1ae8597565c799c57ed00f0e120.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script>
<script>
    tocbot.init({
        
        tocSelector: '.js-toc',
        
        contentSelector: '.js-toc-content',
        
        headingSelector: 'h1, h2, h3',
        
        hasInnerContainers: true,
    });
</script>

<script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine"></script>
<script type="text/javascript">
    var GUEST = ['nick', 'mail', 'link'];
    var meta = 'nick,mail';
    meta = meta.split(',').filter(function (item) {
        return GUEST.indexOf(item) > -1;
    });
    new Valine({
        el: '#vcomments',
        verify: null ,
        notify: null ,
        appId: 'IyAB0PSPRazTPDxitO1ddQ7O-gzGzoHsz',
        appKey: '5rBJTq4KidYF33eXwvRVhtEH',
        placeholder: 'enjoy~',
        avatar: 'mm',
        meta: meta,
        pageSize: '10' || 10,
        visitor: false 
});
</script>

  </body>
</html>
